package ventureco.communication;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ThreadClient extends Thread{

	 private String serverHostname = null;
	    private int serverPort = 0;
	    private byte[] data = null;
	    private Socket sock = null;
	    private InputStream sockInput = null;
	    private OutputStream sockOutput = null;
	    
	    private int method;

	    public ThreadClient(String serverHostname, int serverPort, byte[] data, int method){
		this.serverHostname =  serverHostname;
		this.serverPort = serverPort;
		this.data = data;
		this.method = method;
	    }
	    
	    public void sendSomeMessages(int iterations) {
		System.err.println("Opening connection to "+serverHostname+" port "+serverPort);
		try {
		    sock = new Socket(serverHostname, serverPort);
		    sockInput = sock.getInputStream();
		    sockOutput = sock.getOutputStream();
		}
		catch (IOException e){
		    e.printStackTrace(System.err);
		    return;
		}

		//System.err.println("About to start writing to socket.");

		byte[] buf = new byte[data.length];
		int bytes_read = 0;
		for(int loopi = 1; loopi <= iterations; loopi++) {
		    try {
		    	
//		    	byte[] newData = new byte[data.length + 1];
//		    	if(method == 0) newData[0] = 0;
//		    	else newData[0] = 1;
//				System.arraycopy(data, 0, newData, 1, data.length);	
		    	
			 sockOutput.write(data, 0, data.length);
			bytes_read = sockInput.read(buf, 0, buf.length);
		    }
		    catch (IOException e){
			e.printStackTrace(System.err);
		    }
//		    if(bytes_read < data.length) {
//			System.err.println("run: Sent "+data.length+" bytes, server should have sent them back, read "+bytes_read+" bytes, not the same number of bytes.");
//		    }
//		    else {
//			System.err.println("Sent "+bytes_read+" bytes to server, msg = "+(new String(data)));
//		    }

		    // Sleep for a bit so the action doesn't happen to fast - this is purely for reasons of demonstration, and not required technically.
		    try { Thread.sleep(50);} catch (Exception e) {}; 
		}
		//System.err.println("Done reading/writing to/from socket, closing socket.");

		try {
		    sock.close();
		}
		catch (IOException e){
		    System.err.println("Exception closing socket.");
		    e.printStackTrace(System.err);
		}
	    }

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			sendSomeMessages(1);
		}
}